#include "tcpclient.h"
#include "qcoreapplication.h"
#include "Core/messagedispatcher.h"
TcpClient *TcpClient::m_TcpClient=nullptr;
QMutex TcpClient::TcpClientMutex;
TcpClient *TcpClient::get_instance()
{
    if(m_TcpClient==nullptr){
        QMutexLocker locker(&TcpClientMutex);
        if(m_TcpClient==nullptr){
            m_TcpClient=new TcpClient;
            qAddPostRoutine(destroy_instance);
        }
    }
    return m_TcpClient;
}

QString TcpClient::getUserName()
{
    return UserName;
}

void TcpClient::SetUserName(QString UserName)
{
    this->UserName=UserName;
}
TcpClient::TcpClient(QObject *parent) : QObject(parent)
{
    InitFormConfig();
    connect(&m_TcpSocket,&QTcpSocket::connected,
            this,&TcpClient::TcpConnectStatus);
    connect(&m_TcpSocket,&QTcpSocket::readyRead,
            this,&TcpClient::RecvMsg);
}
int TcpClient::InitFormConfig(QString FileName)
{
    QFile file(FileName);
    if(!file.open(QIODevice::ReadOnly)){
        return 1;//文件不存在返回1
    }
    QByteArray ConfigData=file.readAll();
    QString Data(ConfigData);
    Data.replace("\r\n"," ");
    QStringList splitData=Data.split(' ');
    this->ServerIp=splitData[0];
    this->ServerPort=splitData[1].toUShort();
    return 0;
}

QTcpSocket& TcpClient::getUserTcp()
{
    return m_TcpSocket;
}

QString TcpClient::GetUserName()
{
    return UserName;
}

bool TcpClient::Do_Connect()
{
    InitFormConfig();
    m_TcpSocket.connectToHost(this->ServerIp,this->ServerPort);
    if (!m_TcpSocket.waitForConnected(3)) {
        emit sigConnectFail(m_TcpSocket.errorString());
        return false;
    }
    emit sigConnectSuccess();
    return true;
}

void TcpClient::SendMsg(myuint Type, QJsonObject Info)
{
    QJsonDocument doc(Info);
    QString Body=doc.toJson();
    PDU *MSG=get_PDU(Body.toUtf8().toStdString().length());
    MSG->MessageType=Type;
    memcpy((char*)MSG+sizeof(PDU),
           Body.toUtf8().toStdString().c_str(),
           Body.toUtf8().toStdString().length());
    m_TcpSocket.write((char*)MSG,MSG->PDULength);

    free(MSG);
    MSG=nullptr;

}

void TcpClient::TcpConnectStatus()
{

}

void TcpClient::RecvMsg()
{
    myuint length=0;
    m_TcpSocket.read((char*)&length,sizeof(length));
    myuint MsgLen=length-sizeof(PDU);
    PDU* recvData=get_PDU(MsgLen);
    m_TcpSocket.read((char*)recvData+sizeof(myuint),length-sizeof(myuint));
    MessageDispatcher::GetInstance()
            ->DoHandler(recvData->MessageType,std::shared_ptr<PDU>(recvData,std::free));
//    switch (recvData->MessageType) {
//    case MSG_TYPE_ADD_FRIEND_RESPOND:
//        break;
    recvData=nullptr;
}


void TcpClient::destroy_instance()
{
    //qDebug()<<__FILE__<<__FUNCTION__<<__LINE__;
    if(m_TcpClient==nullptr)return;
    m_TcpClient->m_TcpSocket.disconnectFromHost();
    if(m_TcpClient->m_TcpSocket.state()==QAbstractSocket::ConnectedState){
        m_TcpClient->m_TcpSocket.waitForDisconnected(1);
    }
    delete m_TcpClient;
    m_TcpClient=nullptr;
}
